package com.lzp.java.concurrent.threadcore.threadandobject.object;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 使用wait和notify实现生产者和消费者模式--容器采用链表
 *
 * @author lzp
 * @date 2020/02/07
 */
public class ProducerConsumerModelByWaitAndNotify {
    public static void main(String[] args) {
        // 创建仓库
        Storage storage = new Storage();
        // 创建生产者消费者线程
        Thread producer = new Thread(new ProducerTask(storage));
        Thread consumer = new Thread(new ConsumerTask(storage));
        producer.start();
        consumer.start();
    }
}

class ProducerTask implements Runnable {
    private Storage storage;

    public ProducerTask(Storage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        // 生产100个产品
        for (int i = 0; i < 100; i++) {
            storage.put();
        }
    }
}

class ConsumerTask implements Runnable {
    private Storage storage;

    public ConsumerTask(Storage storage) {
        this.storage = storage;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            storage.take();
        }
    }
}

class Storage {
    private int maxSize;
    private Queue<Date> storage;

    public Storage() {
        this.maxSize = 10;
        this.storage = new LinkedList<>();
    }

    /**
     * wait和notify需要首先获取到锁，因此需要使用synchronized方法或者同步代码块
     */
    public synchronized void put() {
        // 仓库已满，无法生产更多产品，让出锁
        while (storage.size() == maxSize) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.add(new Date());
        System.out.println("生产者生产产品，此时仓库产品数：" + storage.size());
        // 通知消费者消费
        notify();
    }

    public synchronized void take() {
        // 仓库为空，无法获取到产品，线程让出锁
        while (storage.size() == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        storage.poll();
        System.out.println("消费者消费产品，此时仓库产品数：" + storage.size());
        // 通知生产者生产
        notify();
    }
}